package org.daochong.spring.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.daochong.lang.JsonAccessException;
import org.daochong.web.WebUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class JsonErrorInterceptor implements HandlerInterceptor {

	public static int DEFAULT_ERROR_CODE = 1;

	private boolean withException;

	private List<String> debugIps;

	public List<String> getDebugIps() {
		return debugIps;
	}

	public void setDebugIps(List<String> debugIps) {
		this.debugIps = debugIps;
	}

	public boolean isWithException() {
		return withException;
	}

	public void setWithException(boolean withException) {
		this.withException = withException;
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (ex != null) {
			JsonAccessException je = null;
			if (ex instanceof JsonAccessException) {
				je = (JsonAccessException) ex;
			} else {
				je = new JsonAccessException(DEFAULT_ERROR_CODE, ex);
			}
			String ip = WebUtils.getIpAddress(request);
			if ("0:0:0:0:0:0:0:1".equals(ip) ||(this.getDebugIps() != null && this.getDebugIps().contains(ip))) {
				je.setShowException(true);
			}
			je.setHost(WebUtils.getHost(request));
			WebUtils.writeJSON(je.toString(), response);
		}
	}

}
